
// 将headerAuth对象转换为表单需要的格式
export const convertHeaderAuthToFormData = (headerAuth: any) => {
  if (!headerAuth || Object.keys(headerAuth).length === 0) {
    return { type: '无' };
  }

  const authType = Object.keys(headerAuth)[0];
  const authValue = headerAuth[authType];

  if (authType === 'Bearer') {
    return {
      type: 'Bearer',
      name: authValue.value ? authValue.value : authValue.secret ? '        ' : '',
      secret: authValue.secret || null
    };
  } else if (authType === 'Basic') {
    try {
      // const decoded = Buffer.from(authValue.value || '', 'base64').toString();
      // const [username, password] = decoded.split(':');
      return {
        type: 'Basic',
        username: authValue.username ? authValue.username : authValue.secret ? '        ' : '',
        password: authValue.password ? authValue.password : authValue.secret ? '        ' : '',
        secret: authValue.secret || null
      };
    } catch (error) {
      return {
        type: '无'
      };
    }
  } else {
    // 自定义类型
    const customAuth = Object.entries(headerAuth).map(([key, value]: [string, any]) => ({
      key,
      value: value.value ? value.value : value.secret ? '        ' : '',
      secret: value.secret || null
    }));
    return {
      type: '自定义',
      customAuth
    };
  }
};

export const formatAuthData = (value: object) => {
  if (Object.keys(value).length === 0) {
    return '无'
  } else {
    const authType = Object.keys(value)[0];
    if (authType === 'Bearer' || authType === 'Basic') {
      return authType
    } else {
      return '自定义'
    }
  }
};

export const formatAuthConfig = (value: object) => {
  if (Object.keys(value).length === 0) {
    return {}
  } else {
    const authType = Object.keys(value)[0];
    if (authType === 'Basic') {
      const basicValue = value as any;
      const credentials = `${basicValue.Basic.username}:${basicValue.Basic.password}`;
      const base64Credentials = Buffer.from(credentials).toString('base64');
      const newHeaderAuth = {
        Basic: {
          // ...basicValue.Basic,
          secret: basicValue.Basic.secret,
          value: base64Credentials,
        }
      };
      return newHeaderAuth
    } else {
      return value;
    }
  }
};